import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_module/beans/ShareBean.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/beans/share.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/commom/commom.dart';
import 'package:flutter_module/event/deleteShare_event.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:flutter_module/widget/view/LoadingDialog.dart';
import 'package:oktoast/oktoast.dart';

import '../../DemoLocalizations.dart';

class RumorCard extends StatelessWidget {
  final Result model;
  final EdgeInsetsGeometry margin;
  // final GestureTapCallback onTap;

  RumorCard(this.model, {@required this.margin});

  static TextStyle defStyle = TextStyle(
    color: Colors.white,
    fontWeight: FontWeight.w600,
  );

  @override
  Widget build(BuildContext context) {
    // print(DateTime.now().millisecondsSinceEpoch);
    // print(model);
    // print(model.productName);
    TextEditingController fenxiangrenname = new TextEditingController();
    var _receiveNotification;
    var _limiteNotification;
    var _limiteNotificationNumber = 0;
    var a = DateTime.now().add(new Duration(days: 1)).millisecondsSinceEpoch;
    String lev;
    switch (model.level.toString()) {
      case "0":
        lev = (DemoLocalizations.of(context).ControlSwitch);
        break;
      case "1":
        lev = (DemoLocalizations.of(context).SettingParameters);
        break;
      case "2":
        lev = (DemoLocalizations.of(context).ViewCamera);
        break;
      case "3":
        lev = ("恢复出厂设置");
        break;
    }
    return new GestureDetector(
      onTap: () {
        showDialog(
            context: context,
            builder: (context) {
              String label = 'test';
              return StatefulBuilder(
                builder: (context, state) {
                  print('label = $label');
                  return CupertinoAlertDialog(
                    title: Text(DemoLocalizations.of(context).Modifyshare),
                    content: Card(
                      elevation: 0.0,
                      child: Column(children: <Widget>[
                        Text(DemoLocalizations.of(context).SharerAccount +
                            ': ' +
                            model.heAccount),
                            
                        FlatButton(
                            onPressed: () {
                              _onClick((String response) {
                                print(response);
                                var now = DateTime.parse(response);
                                a = now.millisecondsSinceEpoch; // 时间戳
                                print(a);
                                state(() {
                                  _receiveNotification =
                                      now.toString().substring(0, 16);
                                });
                              }, context);
                            },
                            child: Text(
                              '${_receiveNotification ?? DemoLocalizations.of(context).clicktime}',
                              style: TextStyle(color: Colors.blue),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Center(
                          child: PopupMenuButton(
                            child: Text(
                              _limiteNotification ??
                                  DemoLocalizations.of(context).clickpermission,
                              style: TextStyle(color: Colors.blue),
                            ),
                            tooltip: "长按提示",
                            initialValue: "hot",
                            padding: EdgeInsets.all(0.0),
                            itemBuilder: (BuildContext context) {
                              return <PopupMenuItem<String>>[
                                
                                PopupMenuItem<String>(
                                  child: Text(DemoLocalizations.of(context)
                                      .ControlSwitch),
                                  value: "0",
                                ),
                                PopupMenuItem<String>(
                                  child: Text(DemoLocalizations.of(context)
                                      .SettingParameters),
                                  value: "1",
                                ),
//                                                          PopupMenuItem<String>(child: Text("恢复出厂设置"), value: "2",),
                                PopupMenuItem<String>(
                                  child: Text(
                                      DemoLocalizations.of(context).ViewCamera),
                                  value: "2",
                                ),
                              ];
                            },
                            onSelected: (String action) {
                              switch (action) {
                                case "0":
//                                                            print("控制开关");
                                  _limiteNotification =
                                      DemoLocalizations.of(context)
                                          .ControlSwitch;
                                  _limiteNotificationNumber = 0;
                                  break;
                                case "1":
//                                                            print("设置参数");
                                  _limiteNotification =
                                      DemoLocalizations.of(context)
                                          .SettingParameters;
                                  _limiteNotificationNumber = 1;
                                  break;
                                case "2":
//                                                            print("查看摄像头");
                                  _limiteNotification =
                                      DemoLocalizations.of(context).ViewCamera;
                                  _limiteNotificationNumber = 2;
                                  break;
                              }
                              state(() {});
                            },
                            onCanceled: () {
                              print("onCanceled");
                            },
                          ),
                        ),
                      ]),
                    ),
                    actions: <Widget>[
                      CupertinoDialogAction(
                        child: Text(DemoLocalizations.of(context).cancel),
                        onPressed: () {
                          Navigator.pop(context);
//                              print("取消");
                        },
                      ),
                      CupertinoDialogAction(
                        child: Text(DemoLocalizations.of(context).confirm),
                        onPressed: () {
                          ShareBean shareBean = new ShareBean();
                          //等级
                          shareBean.level = _limiteNotificationNumber;
                          shareBean.chipid = model.chipid;
                          shareBean.heAccount = model.heAccount;
                          //时间
                          shareBean.time = a;
                          shareBean.myAccount = model.myAccount;
                          shareBean.id = model.id;
                          print(shareBean.id);
                          print(shareBean.chipid);
                          print(shareBean.myAccount);
                          print(shareBean.time);
                          print(shareBean.heAccount);
                          print(shareBean.level);
                          // SHARE
                          ApiService().ShareESP((Response response) {
                            if (response != null) {
                              ConmmonResult conmmonResult =
                                  ConmmonResult.fromJson(response.data);
                              if (conmmonResult.success) {
                                showToast(DemoLocalizations.of(context)
                                    .Modificationsucceeded);
                                Navigator.pop(context);
                                Application.eventBus
                                    .fire(new DeleteShare_event());
                              } else {
                                showToast(conmmonResult.message);
                              }
                            }
                          }, shareBean, true);
                        },
                      ),
                    ],
                  );
                },
              );
            });
      },
      onLongPress: () {
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
//                title: Text("不可逆操作提示"),
                content: SizedBox(
                  child: Text(DemoLocalizations.of(context).withdrawshare),
                ),
                actions: <Widget>[
                  CupertinoDialogAction(
                    child: Text(DemoLocalizations.of(context).cancel),
                    onPressed: () {
                      Navigator.pop(context);
//                      print("取消");
                    },
                  ),
                  CupertinoDialogAction(
                    child: Text(DemoLocalizations.of(context).confirm),
                    onPressed: () {
//                      print("确定");
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (BuildContext context) {
                            return new LoadingDialog(
                              text: DemoLocalizations.of(context)
                                  .Sharinrecovering,
                            );
                          });
                      ApiService().deleteShare((Response response) {
                        if (response != null) {
                          ConmmonResult conmmonResult =
                              ConmmonResult.fromJson(response.data);
                          if (conmmonResult.success) {
                            Application.eventBus.fire(new DeleteShare_event());
                            showToast(DemoLocalizations.of(context)
                                .CancelledSuccessfully);
                            Navigator.pop(context);
                            Navigator.pop(context);
                          } else {
                            Navigator.pop(context);
                          }
                        }
                      }, model.id);
                    },
                  ),
                ],
              );
            });
      },
      child: new Container(
        margin: margin,
        padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(5.0)),
          gradient: LinearGradient(
            colors: [Color(0xffFFFFF0), Color(0xffAFEEEE)],
          ),
          //背景
          color: Colors.white,
          //设置四周边框
          border: new Border.all(width: 1, color: Colors.black),
        ),
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // FlatButton(onPressed: null, child: Text('data')),
            new Space(),
            new Space(),
            Container(
              width: 130,
              // height: 30,
              decoration: new BoxDecoration(
                  // border: new Border.all(color: Color(0xFFFF0000), width: 0.5),
                  // color: Colors.blue,
                  borderRadius: new BorderRadius.circular((5.0))),
              alignment: Alignment.center,
              child: new Text(
                '${model?.heAccount ?? '未知'}:'+model.productName?? '',
                // model.heAccount+model.productName,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                ),
                maxLines: 5,
                overflow: TextOverflow.ellipsis,
              ),
            ),

            // new SizedBox(
            //   width: 38.0,
            //   child:
            //   new Text(
            //     '${model?.heAccount ?? '未知'}',
            //     textAlign: TextAlign.center,
            //     style: TextStyle(
            //       color: Colors.white,
            //     ),
            //     maxLines: 6,
            //     overflow: TextOverflow.ellipsis,
            //   ),
            // ),
            new Expanded(child: new Space(),
            flex : 1),
            // new Expanded(
            //   child: new Container(
            //     height: 30,
            //     decoration: new BoxDecoration(
            //         // border: new Border.all(color: Color(0xFFFF0000), width: 0.5),
            //         color: Colors.blue,
            //         borderRadius: new BorderRadius.circular((5.0))),
            //     alignment: Alignment.center,
            //     child: new Text(
            //       '${model?.productName ?? '未知'}',
            //       style: TextStyle(
            //         color: Colors.white,
            //       ),
            //       maxLines: 1,
            //       overflow: TextOverflow.ellipsis,
            //       textAlign: TextAlign.center,
            //     ),
            //     // color: Colors.blue,
            //     //margin: const EdgeInsets.all(5.0),
            //     //padding: const EdgeInsets.all(5.0),
            //   ),
            //   flex: 1,
            // ),
            // new Space(),

            new Container(
              alignment: Alignment.centerRight,
              padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 6.0),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.all(Radius.circular(5.0)),
              ),
              margin: EdgeInsets.symmetric(vertical: 5.0),
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Row(
                    children: <Widget>[
                      new Visibility(
                        visible:
                            model.time > DateTime.now().millisecondsSinceEpoch,
                        child: new Text(
                          DateTime.fromMillisecondsSinceEpoch(model.time)
                              .toString()
                              .substring(0, 16),
                          style: TextStyle(color: Colors.white),
                          maxLines: 2,
                        ),
                      ),
                      new Visibility(
                        visible:
                            model.time < DateTime.now().millisecondsSinceEpoch,
                        child: new Text(
                          "         " +
                              DemoLocalizations.of(context).Expired +
                              "          ",
                          style: TextStyle(color: Colors.deepOrange),
                        ),
                      ),
                    ],
                  ),
                  new Space(),
                  new Visibility(
                    visible: true,
                    child: new Text(
                      lev.toString(),
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  new GestureDetector(
                    child: new Padding(
                      padding: EdgeInsets.all(3.0),
                    ),
                  ),
                ],
              ),
            ),
            new Container(
              child: Container(
                alignment: Alignment.center,
                child: MaterialButton(
                  minWidth: 50,
                  padding: EdgeInsets.all(2),
                  onPressed: () {
                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return CupertinoAlertDialog(
//                                  title: Text("不可逆操作提示"),
                            content: SizedBox(
                              child: Text(
                                  DemoLocalizations.of(context).withdrawshare),
                            ),
                            actions: <Widget>[
                              CupertinoDialogAction(
                                child:
                                    Text(DemoLocalizations.of(context).cancel),
                                onPressed: () {
                                  Navigator.pop(context);
//                                        print("取消");
                                },
                              ),
                              CupertinoDialogAction(
                                child:
                                    Text(DemoLocalizations.of(context).confirm),
                                onPressed: () {
//                                        print("确定");
                                  showDialog(
                                      context: context,
                                      barrierDismissible: false,
                                      builder: (BuildContext context) {
                                        return new LoadingDialog(
                                          text: DemoLocalizations.of(context)
                                              .Sharinrecovering,
                                        );
                                      });
                                  ApiService().deleteShare((Response response) {
                                    if (response != null) {
                                      ConmmonResult conmmonResult =
                                          ConmmonResult.fromJson(response.data);
                                      if (conmmonResult.success) {
                                        showToast(DemoLocalizations.of(context)
                                            .CancelledSuccessfully);
                                        Application.eventBus
                                            .fire(new DeleteShare_event());
                                        Navigator.pop(context);
                                        Navigator.pop(context);
                                      } else {
                                        showToast(conmmonResult.message);
                                        Navigator.pop(context);
                                      }
                                    }
                                  }, model.id);
                                },
                              ),
                            ],
                          );
                        });
                  },
                  child: Column(
                    children: <Widget>[
                      Icon(
                        Icons.delete_forever,
                        color: Colors.red,
                      ),
                      Text('del',
                          style: TextStyle(
                            color: Colors.red,
                          )),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

_onClick(Function callback, BuildContext context) {
  if (Platform.localeName.startsWith('en')) {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now(),
        maxTime: DateTime(2109, 6, 7, 1, 1, 1), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      print('confirm $date');
      callback(date.toString());
    }, currentTime: DateTime.now(), locale: LocaleType.en);
  } else {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now(),
        maxTime: DateTime(2109, 6, 7, 1, 1, 1), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      print('confirm $date');
      callback(date.toString());
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }
}
